package com.jxl.wechat.controller;

import com.jxl.wechat.handler.WeChatMsgFactory;
import com.jxl.wechat.handler.WeChatMsgHandler;
import com.jxl.wechat.util.MessageUtil;
import com.jxl.wechat.util.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

/**
 * 微信回调
 */
@RestController
@Slf4j
public class CallBackController {

    private final static  String  TOKEN = "ivbeeiwvu";

    @Resource
    private WeChatMsgFactory weChatMsgFactory;

    /**
     * 回调消息校验
     */
    @GetMapping("callback")
    public String callback(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数：signature:{}，timestamp:{}，nonce:{}，echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1.getSHA1(TOKEN, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }


    @PostMapping(value = "callback", produces = "application/xml;charset=UTF-8")
    public String callback(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信消息：requestBody：{}", requestBody);
        Map<String, String> map = MessageUtil.parseXml(requestBody);
        String msgType = map.get("MsgType");//消息类型
        //如果是事件类型
        String event = map.get("Event")==null? "":map.get("Event");

        //构建msgType
        StringBuilder sb = new StringBuilder();
        sb.append(msgType);
        if (!"".equals(event)){
            sb.append(".");
            sb.append(event);
        }
        //接下来构建handler
        WeChatMsgHandler handler = weChatMsgFactory.getHandler(sb.toString());
        if (handler==null){
            return "unKnow";
        }
        String deal = handler.deal(map);
        return deal;
    }






}
